import { v4 } from 'uuid'
import { computed, readonly, ref } from 'vue'
import { defineStore } from 'pinia'

export const useImageCutStore = defineStore('image-cut', () => {
  const _file = ref(null)
  const isOpen = computed(() => !!_file.value)
  const cutAction = ref(() => {})

  /**
   * 開啟圖片裁剪彈窗
   * @param params.file {File}
   * @param params.onImageCut {function} 裁剪後的圖片回調
   */
  function open({ file, onImageCut = () => {} }) {
    _file.value = file
    cutAction.value = onImageCut
    console.log('useImageCutStore.open', isOpen.value)
  }

  function close() {
    _file.value = null
    cutAction.value = () => {}
    console.log('useImageCutStore.close', isOpen.value)
  }

  function onImageCut(file) {
    const cuttedImageFile = new File([file], `${v4()}.jpeg`, { type: 'image/jpeg' })
    cutAction.value(cuttedImageFile)
  }

  return { file: readonly(_file), isOpen, open, close, onImageCut }
})
